package HOT;

import java.util.List;

/**
 * Author  zxy
 * Date  2023/6/7 下午 5:40
 */
public class WordSplit {

    public boolean wordBreak(String s, List<String> wordDict) {

        // 构造字典树
        // HOT.Trie trie = new HOT.Trie();
        // for (String ss : wordDict) {
        //     trie.insert(ss);
        // }

        int len = s.length();
        boolean[] dp = new boolean[len + 1];
        dp[0] = true;

        for (int i = 1; i <= len; i++) {
            for (int j = 0; j < i; j++) {
                if (dp[j] && wordDict.contains(s.substring(j, i))) {
                    dp[i] = true;
                    break;
                }
            }
        }


        return dp[len];
    }

    class Trie {
        Trie children[];
        boolean isEnd;

        public Trie() {
            children = new Trie[26];
            isEnd = false;
        }

        public void insert(String word) {
            Trie node = this;

            for (char c : word.toCharArray()) {
                int index = c - 'a';
                if (node.children[index] == null) {
                    node.children[index] = new Trie();
                }

                node = node.children[index];
            }

            node.isEnd = true;
        }

        public boolean find(String word) {
            Trie node = searchPrefix(word);

            return node != null && node.isEnd;
        }

        public boolean startWith(String prefix) {
            Trie node = searchPrefix(prefix);

            return node != null;
        }

        public Trie searchPrefix(String prefix) {
            Trie node = this;

            for (char c : prefix.toCharArray()) {
                int index = c - 'a';
                if (node.children[index] == null) {
                    return null;
                }

                node = node.children[index];
            }

            return node;
        }
    }
}